from django.utils import simplejson

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

from models import *

class TagHistoriesAdd(webapp.RequestHandler):
	def get(self):
		user = NarisaUser.all().filter('vcKey =', self.request.get('vcKey')).fetch(1)

		if (len(user) == 0):
			self.response.out.write('{ error:401, message: "Unauthorized: bad vcKey"}')
			return

		tagName = self.request.get('tagName').strip()

		if (tagName == ''):
			self.response.out.write('{ error:400, message: "tagName is empty"}')
			return

		topicId = self.request.get('topicId').strip()

		if (topicId.isdigit() is not True):
			self.response.out.write('{ error:400, message: "topicId:%s is not digit"}' % topicId)
			return

		color = self.request.get('color').strip()

		TagHistory.tagTopic(tagName, user[0], int(topicId), color)
		self.redirect('/topicStats/byTopics?topics=' + topicId + '&vcKey=' + user[0].vcKey)

class TagHistoriesDel(webapp.RequestHandler):
	def get(self):
		user = NarisaUser.all().filter('vcKey =', self.request.get('vcKey')).fetch(1)

		if (len(user) == 0):
			self.response.out.write('{ error:401, message: "Unauthorized: bad vcKey"}')
			return

		tag = Tag.find(self.request.get('tagName'))

		if (tag == None):
			self.response.out.write('{ error:400, message: "tag:%s is not existed"}' % self.request.get('tagName'))
			return

		topicId = self.request.get('topicId').strip()

		if (topicId.isdigit() is not True):
			self.response.out.write('{ error:400, message: "topicId:%s is not digit"}' % topicId)
			return

		TagHistory.untagTopic(tag, user[0], int(topicId))
		self.redirect('/topicStats/byTopics?topics=' + topicId + '&vcKey=' + user[0].vcKey)

application = webapp.WSGIApplication(
		[
			('/tagHistories/add', TagHistoriesAdd),
			('/tagHistories/del', TagHistoriesDel)
		],
		debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()

